<template>
  <el-dialog title="补领料" :visible.sync="showDialog" top="0" :close-on-click-modal="false" @close="cancel">
    <el-form v-if="selectedItem !== null" ref="form" :model="formData" class="el-form">
      <el-form-item label="补领物料：" class="w100p" :rules="[{ required: true }]">
        <div class="list">
          <div v-for="(item, index) in actTaskRawMaterialList" :key="index" class="list-item">
            <el-select v-model="item.materialNo" placeholder="请选择原料" @change="changeRawMaterial($event, index)">
              <el-option v-for="innerItem in selectedItem.taskRawMaterialList" :key="innerItem.materialNo" :label="innerItem.materialName" :value="innerItem.materialNo" />
            </el-select>
            <div class="input-group">
              <el-input-number :precision="0" v-model="item.num" type="number" :min="0" placeholder="请输入数量" clearable />
              <div class="append">{{ item.unitName }}</div>
            </div>
            <i class="remove-btn el-icon-remove-outline" @click="removeRawMaterial(index)"></i>
          </div>
          <div class="add-btn">
            <i class="el-icon-circle-plus-outline" @click="addRawMaterial"></i>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
      <el-button :disabled="actTaskRawMaterialList.length === 0" :loading="saveLoading" type="primary" class="savebtn" @click="save()">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import api from '@/api/processing-management/process-task-manage/index';
import moment from 'moment';
export default {
  components: {},
  filters: {
    formateTime: function(value) {
      return moment(value).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  props: {
    value: Boolean,
    selectedItem: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      formDataDefault: {},
      formData: {},
      saveLoading: false,
      showDialog: false,
      actTaskRawMaterialList: []
    };
  },
  watch: {
    value(v) {
      this.showDialog = v;
      if (v) {
        this.init();
      }
    }
  },
  created() {
    this.reset();
  },
  mounted() {},
  methods: {
    reset() {
      this.formData = JSON.parse(JSON.stringify(this.formDataDefault));
      this.actTaskRawMaterialList = [];
    },
    init() {
      const { selectedItem, formData } = this;
      if (selectedItem) {
        for (const key in formData) {
          if (Object.hasOwnProperty.call(formData, key)) {
            formData[key] = selectedItem[key];
          }
        }
        this.$refs['form']?.resetFields();
      }
    },
    save() {
      const { actTaskRawMaterialList } = this;
      const paylod = JSON.parse(JSON.stringify(actTaskRawMaterialList));
      let err = '';
      for (let i = 0; i < actTaskRawMaterialList.length; i++) {
        const element = actTaskRawMaterialList[i];
        if (element.materialNo === '' || element.num === '') {
          err = '物料信息请填写完整';
          break;
        }
      }
      if (err !== '') {
        this.$message.error(err);
        return;
      }
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.saveLoading = true;
          api
            .repairPickingTask(paylod)
            .then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.close();
                this.$emit('reflash');
              }
            })
            .finally(_ => {
              this.saveLoading = false;
            });
        }
      });
    },
    close() {
      setTimeout(() => {
        this.reset();
        this.$refs['form'].resetFields();
      }, 250);
      this.$emit('input', false);
    },
    cancel() {
      setTimeout(() => {
        this.reset();
        this.$refs['form'].resetFields();
      }, 250);
      this.$emit('input', false);
    },
    addRawMaterial() {
      this.actTaskRawMaterialList.push({
        materialNo: '',
        num: '',
        unitName: '',
        taskId: this.selectedItem.taskId
      });
    },
    removeRawMaterial(index) {
      this.actTaskRawMaterialList.splice(index, 1);
    },
    changeRawMaterial(v, index) {
      const { selectedItem } = this;
      const find = selectedItem.taskRawMaterialList.find(i => i.materialNo === v);
      this.actTaskRawMaterialList[index].unitName = find.unitName;
      this.actTaskRawMaterialList[index].num = 0;
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__label {
  min-width: 120px !important;
}
.input-group {
  display: flex;
  align-items: center;
  width: 100%;
  > * {
    &:first-of-type {
      flex: 1;
      width: auto;
    }
  }
  .append {
    flex: 0 0 100px;
    background-color: #f5f7fa;
    color: #909399;
    position: relative;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 0 20px;
    width: 100%;
    box-sizing: border-box;
    height: 36px;
    border-left: none;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    text-align: center;
  }
}
::v-deep .el-form-item__content {
  min-height: 36px;
  align-items: center;
}
.list {
  width: 100%;
  .list-item {
    margin-bottom: 5px;
    display: flex;
    align-items: center;
    > * {
      &:first-child {
        margin-right: 5px;
        flex: 0 0 50%;
      }
      &:last-child {
        margin-left: 5px;
      }
    }
    &:last-of-type {
      margin-bottom: 0;
    }
    .remove-btn {
      cursor: pointer;
      font-size: 18px;
      &:hover {
        color: #f56c6c;
      }
    }
  }
  .add-btn {
    cursor: pointer;
    font-size: 20px;
  }
}
</style>
